/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package PuriON;

import javax.media.*;
import java.net.*;
import java.io.*;
import javax.media.control.*;
import javax.media.format.*;
import javax.media.protocol.*;

/**
 *
 * @author hyukmini
 */
public class PURION_Receive {

    private String remoteSource = null;
    private String localDestination = null;

    public PURION_Receive(String src, String path) {

        remoteSource = src;
        localDestination = path;
    }
    
    
    
    public void startConvert() {
        URL mediaURL = null;
        URL destURL = null;
        try {
            mediaURL = new URL(remoteSource);
            destURL = new URL(mediaURL.getProtocol(), mediaURL.getHost(), localDestination);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        Processor processor;
        PURION_StateHelper sh = null;
        try {
            MediaLocator mrl = null;
            if ((mrl = new MediaLocator(mediaURL)) == null) {
                return;
            }
// 해당 URL에 맞는 Player 을 만든다.
            processor = Manager.createProcessor(mrl);
            sh = new PURION_StateHelper(processor);
            if (!sh.configure(10000)) {
                System.exit(-1);
            }
            TrackControl[] trackControls = processor.getTrackControls();
            int audioTrackIndex = 0;
            for (int i = 0; i < trackControls.length; i++) {
                if (trackControls[i].getFormat() instanceof AudioFormat) {
                    audioTrackIndex = i;
                } else if (trackControls[i].getFormat() instanceof VideoFormat) {
                    trackControls[i].setEnabled(false);
                }
            }
            trackControls[audioTrackIndex].setEnabled(true);
            trackControls[audioTrackIndex].setFormat(new AudioFormat(AudioFormat.MPEGLAYER3));
            processor.setContentDescriptor(new FileTypeDescriptor(FileTypeDescriptor.MPEG_AUDIO));
            if (!sh.realize(10000)) {
                System.exit(-1);
            }
            DataSink sink = null;
            MediaLocator dest = new MediaLocator(destURL);
            try {
                sink = Manager.createDataSink(processor.getDataOutput(), dest);
                sink.open();
                sink.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 미디어의 시간까지 플레이
            sh.playToEndOfMedia((int) (processor.getDuration().getSeconds()) * 1000);
            sh.close();
            sink.close();
            System.exit(-1);
        } catch (NoProcessorException e) {
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
    }
}
